# -*- coding: utf-8 -*-
'''
Created on 2010-02-17

@author: Alexey Subbotin
'''
from django.db import models
from sorl.thumbnail.main import DjangoThumbnail
from sorl.thumbnail.fields import ImageWithThumbnailsField
from datetime import datetime
from django.db.models.base import ModelBase
from django.utils.translation import ugettext as _

OPTIONS = (
           ('crop', _('crop')),
           ('max', _('max size')),
           ('upscale', _('upscale')),
           ('autocrop', _('auto crop')),
           ('crop::upscale', _('crop upscale')),
           )

FORMATS= (
           ('jpg', '.JPG'),
           ('png', '.PNG'),
           )
POSITIONS= (
           ('left', _('Left')),
           ('right', _('Right')),
           # ...
           )

class ThumbnailSettings(models.Model):
    title   = models.CharField(_('Title'), max_length=50)
    width   = models.PositiveSmallIntegerField(_('Width'), default=100)
    height  = models.PositiveSmallIntegerField(_('Height'), default=100)
    options = models.CharField(_('Options'), blank=True, max_length=20, null=True, choices=OPTIONS)
    quality = models.PositiveSmallIntegerField(_('Quality'), default=90)
    extension  = models.CharField(_('Extension'), choices=FORMATS, default=FORMATS[0][0], max_length=3)
    css_class  = models.CharField(_('CSS Classes'), choices=POSITIONS, blank=True, max_length=5)
    
    class Meta:
        verbose_name = _('Thumbnail settings')
        verbose_name_plural = _('Thumbnail settings')
      
    def __unicode__(self):
        return u'%s (%s %dx%d %s)' % (self.title, self.extension, self.width, self.height, self.options or '')
    
    def get_thumbnail(self, image):
        opts = []
        if self.options:
            opts.extend(self.options.split('::'))
        return DjangoThumbnail(image.name, (self.width, self.height), opts=opts, quality=self.quality, extension=self.extension)

class ImageGallery(models.Model):
    title       = models.CharField(blank=True, max_length=255, verbose_name=_('Title'))
    pub_date    = models.DateTimeField(blank=True, default=datetime.now, verbose_name=_('Date publication'))
    is_visible  = models.BooleanField(_('Is visible'), default=True)
    thumbnail_settings  = models.ForeignKey(ThumbnailSettings, verbose_name=_('Settings'), blank=True, null=True)
    
    class Meta:
        abstract = True
        verbose_name=_('Image')
        verbose_name_plural=_('Images')
        ordering = ['-pub_date']
      
    def __unicode__(self):
        return self.title
    
    def thumbnail(self):
        if self.thumbnail_settings:
            return self.thumbnail_settings.get_thumbnail(self.image)
        else:
            return self.image.thumbnail
    
    def settings(self):
        if self.thumbnail_settings:
            return self.thumbnail_settings
        else:
            class Dummy(dict): 
                def __getitem__(self, key):
                    return ''
            return Dummy()
                

class ImageGalleryMetaClass(ModelBase):
    def __new__(cls, name, bases, attrs):
        attr_meta = attrs.pop('Meta')
        model = getattr(attr_meta, 'model')
        attrs['object'] = models.ForeignKey(model, default=0)
        attrs['image']  = ImageWithThumbnailsField(getattr(attr_meta, 'verbose_name', _('Image')), 
                                                   upload_to=getattr(attr_meta, 'upload_to'), 
                                                   thumbnail=getattr(attr_meta, 'thumbnail'),
                                                   extra_thumbnails=getattr(attr_meta, 'extra_thumbnails', None))
        new_gallery = super(ImageGalleryMetaClass, cls).__new__(cls, name, bases, attrs) #call ModelBase __new__ method
        
        setattr(model, 'get_images', lambda self: new_gallery.objects.select_related('thumbnail_settings').filter(object=self, is_visible=True))
        
        if not hasattr(model, 'col_number') and hasattr(attr_meta, 'col_number'):
            setattr(model, 'col_number', getattr(attr_meta, 'col_number', 4))
            
        return new_gallery
        
        
        
     

'''
usage case:


#models.py        
class Test(models.Model):
    key=models.IntegerField(null=True, blank=True)
    #optional
    col_number = models.PositiveSmallIntegerField(verbose_name=u"Liczba kolumn w galerii zdjęć", default=4)

from met_gallery.models import ImageGallery, ImageGalleryMetaClass
class TestGallery(ImageGallery):
    __metaclass__ = ImageGalleryMetaClass
    class Meta:
        #reqiured
        model         = Test
        upload_to     = 'uploads/products' #or function
        thumbnail     = {'size': (125, 300), 'options': []}
        
        #optional
        verbose_name = u'Obrazek'
        extra_thumbnails={
            'main_img': {'size': (200, 200), 'options': ()}, 
        }
        col_number = 4
   
   
#admin.py
class TestImageInline(admin.TabularInline):
    model = TestGallery
    extra = 5

class TestAdmin(TinyMCEAdmin):
     inlines = [ProductImageInline,]
     
     
 
#templates first example
{% with object.col_number as col_number %}
    {% include 'gallery_table.html' %}
{% endwith %}

{% with 6 as col_number %}
    {% include 'gallery_table.html' %}
{% endwith %}


#templates second example
{% with object.get_images as object_images %}
{% if object_images %}
{% load table %}
    <table class='image' class='col{{col_number|default:'4'}}'>
       {% table image object_images col_number %}
           {% if table.firstcell %}<tbody>{% endif %}
        {% if table.startrow %}<tr>{% endif %}
               <td{{ image.settings.css_class }}>
                   <h4>{{image.title|default:'&nbsp;'}}</h4>
                   <a href='{{ image.image.url }}'>
                       <img src='{{ image.thumbnail }}' alt='{{image.title}}'>
                   </a>
            </td>
         {% if table.endrow %}</tr>{% endif %}
         {% if table.lastcell %}</tbody>{% endif %}
       {% endtable %}
    </table>
{% endif %} 
{% endwith %}


    
#shell    
t = Test()
for item  in t.get_images()
    item.image.extra_thumbnails.main_img
    item.thumbnail #
    item.settings.css_class # css_class for instance (if not present empty string was returned)
            
'''
   
    